package com.example.voicealarm;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class RingActivity extends AppCompatActivity {
    private TextToSpeech tts;
    private int snoozeCount = 0;
    private Alarm alarm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ring);
        Toast.makeText(RingActivity.this, "测试闹钟触发", Toast.LENGTH_SHORT).show();

        getWindow().addFlags(
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
            WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
            WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
            WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
            WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
        );
        hideSystemUI();

        alarm = getIntent().getParcelableExtra("alarm");
        if (alarm == null) {
            android.util.Log.e("RingActivity", "No alarm data received");
            finish();
            return;
        }
        android.util.Log.d("RingActivity", "Received alarm with text: " + alarm.ttsText);
        snoozeCount = getIntent().getIntExtra("snooze_count", 0);

        setupViews();
        playTts();
        setupAutoSnooze();
    }

    private void hideSystemUI() {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN);
    }

    private void setupViews() {
        TextView tvTts = findViewById(R.id.tv_tts);
        tvTts.setText(alarm.ttsText);

        Button btnDismiss = findViewById(R.id.btn_dismiss);
        Button btnSnooze = findViewById(R.id.btn_snooze);

        btnDismiss.setOnClickListener(v -> dismiss());
        btnSnooze.setOnClickListener(v -> snooze());
    }

    private void playTts() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        
        tts = new TextToSpeech(this, status -> {
            if (status == TextToSpeech.SUCCESS) {
                int result = tts.setLanguage(Locale.CHINESE);
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    android.util.Log.e("RingActivity", "Language not supported");
                    return;
                }
                android.util.Log.d("RingActivity", "TTS initialized successfully, speaking: " + alarm.ttsText);
                // 重复播放3次
                for (int i = 0; i < 3; i++) {
                    tts.speak(alarm.ttsText, TextToSpeech.QUEUE_ADD, null, "MSG_" + i);
                }
            } else {
                android.util.Log.e("RingActivity", "TTS initialization failed with status: " + status);
            }
        });
    }

    private void setupAutoSnooze() {
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            if (!isFinishing()) {
                snooze();
            }
        }, 15000);
    }

    private void dismiss() {
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }

        // 设置闹钟为过期状态
        if (alarm != null) {
            // 非重复闹钟才设置过期状态
            if (!alarm.isRepeating()) {
                alarm.expired = true;
                // 更新数据库
                AlarmPreferences preferences = new AlarmPreferences(this);
                List<Alarm> alarms = preferences.loadAlarms();
                for (int i = 0; i < alarms.size(); i++) {
                    if (alarms.get(i).id == alarm.id) {
                        alarms.set(i, alarm);
                        break;
                    }
                }
                preferences.saveAlarms(alarms);
                
                // 发送广播通知MainActivity刷新列表，同时传递当前闹钟状态
                Intent refreshIntent = new Intent("com.example.voicealarm.REFRESH_ALARMS");
                refreshIntent.putExtra("current_alarm", alarm);
                sendBroadcast(refreshIntent);
            } else {
                // 处理重复闹钟的下一次响铃
                Calendar nextAlarmTime = alarm.getNextAlarmTime();

                // 设置下一次闹钟
                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                Intent intent = new Intent(this, AlarmReceiver.class);
                intent.putExtra("alarm", alarm);

                PendingIntent pendingIntent = PendingIntent.getBroadcast(
                        this,
                        (int) alarm.id,
                        intent,
                        PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

                alarmManager.setExactAndAllowWhileIdle(
                        AlarmManager.RTC_WAKEUP,
                        nextAlarmTime.getTimeInMillis(),
                        pendingIntent);
            }
        }

        finish();
    }

    private void snooze() {
        snoozeCount++;

        // 更新闹钟的贪睡状态
        alarm.snoozeCount = snoozeCount;
        alarm.lastSnoozeTime = System.currentTimeMillis();

        // 更新数据库中的闹钟信息
        AlarmPreferences preferences = new AlarmPreferences(this);
        List<Alarm> alarms = preferences.loadAlarms();
        for (int i = 0; i < alarms.size(); i++) {
            if (alarms.get(i).id == alarm.id) {
                alarms.set(i, alarm);
                break;
            }
        }
        preferences.saveAlarms(alarms);

        // 发送广播通知MainActivity刷新列表，同时传递当前闹钟状态
        Intent refreshIntent = new Intent("com.example.voicealarm.REFRESH_ALARMS");
        refreshIntent.putExtra("current_alarm", alarm);
        sendBroadcast(refreshIntent);

        if (snoozeCount >= 3) {
            dismiss();
            return;
        }

        if (tts != null) {
            tts.stop();
        }

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(this, RingActivity.class);
        intent.putExtra("alarm", alarm);
        intent.putExtra("snooze_count", snoozeCount);

        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, (int) alarm.id * 10 + snoozeCount, 
                intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5); // 设置贪睡时间为5分钟

        alarmManager.setExactAndAllowWhileIdle(
                AlarmManager.RTC_WAKEUP, 
                calendar.getTimeInMillis(), 
                pendingIntent);

        finish();
    }

    @Override
    protected void onDestroy() {
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }
}